package com.org.redis.config;

import com.org.redis.utils.FastUtils;
import redis.clients.jedis.*;

import java.util.HashSet;

public class RedisPoolConnection {

    private static JedisPool writeJedisPool;
    private static JedisPool readJedisPool;

    static {
        init2();
    }

    private static void init() {
        JedisPoolConfig config = RedisPoolConfigBuilder.defaultConfig();
        writeJedisPool = new JedisPool(config, RedisConfig.HOST, RedisConfig.PORT, RedisConfig.TIMEOUT, null, RedisConfig.DATABASE, "write-pool");
        readJedisPool = new JedisPool(config, RedisConfig.READ_HOST, RedisConfig.READ_PORT, RedisConfig.TIMEOUT, null, RedisConfig.READ_DATABASE, "read-pool");
    }

    private static void init2() {
        Redis redis = null;
        try {
            redis = (Redis) FastUtils.loadBean(RedisConfig.REDIS_CLASS, RedisConfig.PROPERTIES_NAME);
            redis.init();
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Deprecated
    private static void initCluster() {
        HashSet<HostAndPort> cluster = new HashSet<>();
        cluster.add(new HostAndPort("134.175.117.176",7001));
        cluster.add(new HostAndPort("134.175.117.176",7002));
        cluster.add(new HostAndPort("134.175.117.176",7003));
        cluster.add(new HostAndPort("134.175.117.176",7004));
        cluster.add(new HostAndPort("134.175.117.176",7005));
        cluster.add(new HostAndPort("134.175.117.176",7006));
        JedisCluster jedisCluster = new JedisCluster(cluster);
    }

    protected static Jedis getJedis() {
        if (null != writeJedisPool) {
            return writeJedisPool.getResource();
        }
        if (null != readJedisPool) {
            return readJedisPool.getResource();
        }
        return null;
    }

    protected static Jedis getWriteJedis() {
        return writeJedisPool.getResource();
    }

    protected static Jedis getReadJedis() {
        return readJedisPool.getResource();
    }

    protected static void returnResource(Jedis jedis) {
        if (null != jedis) {
            jedis.close();
        }
    }

    protected static void cloesPool() {
        writeJedisPool.close();
        readJedisPool.close();
    }

}
